# from xml.dom.minidom import parse
import xml.dom.minidom

class DomHander:

    # xml文件路径
    xmlFilePath = ''
    # domtree
    domTree = ''
    # 根节点
    rootElement = ''

    # 解析文件
    def __init__(self, xmlFilePath='movies.xml'):
        try:
            self.xmlFilePath = xmlFilePath
            self.domTree = xml.dom.minidom.parse(xmlFilePath)
        except Exception as e:
            print("解析xml文件异常：" + e)

    # 获取根节点
    def getRootElement(self):
        self.rootElement = self.domTree.documentElement
        return self.rootElement

    # 获取根节点
    def getElement(self, parentElement, tagName):
        return parentElement.getElementsByTagName(tagName)

    # 判断目标节点是否有该属性
    def hasAttribute(self, element, attr):
        return element.hasAttribute(attr)

    # 获取目标节点下的属性
    def getAttribute(self, element, attr):
        return element.getAttribute(attr)

    pass

xmlFilePath = 'movies.xml'
domhandler = DomHander()
rootElement = domhandler.getRootElement()

movies = domhandler.getElement(rootElement, "movie")

#
# # 使用minidom解析器打开xml文档
# DOMTree = xml.dom.minidom.parse("movies.xml")
# collection = DOMTree.documentElement
# print(collection)
# if collection.hasAttribute("shelf"):
#     print("root element :%s" % collection.getAttribute("shelf"))
#
# #在集合中获取所有电影
# movies = collection.getElementsByTagName("movie")


#打印每部电影的详细信息

for movie in movies:
    print ("*****Movie*****")
    if movie.hasAttribute("title"):
        print ("Title: %s" % movie.getAttribute("title"))

    type = movie.getElementsByTagName('type')[0]
    print ("Type: %s" % type.childNodes[0].data)
    format = movie.getElementsByTagName('format')[0]
    print ("Format: %s" % format.childNodes[0].data)
    rating = movie.getElementsByTagName('rating')[0]
    print ("Rating: %s" % rating.childNodes[0].data)
    description = movie.getElementsByTagName('description')[0]
    print ("Description: %s" % description.childNodes[0].data)